package cn.leelei.hibernate.test.entity;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import cn.leelei.hibernate.entity.IDcard;
import cn.leelei.hibernate.entity.Role;
import cn.leelei.hibernate.entity.Role2;
import cn.leelei.hibernate.entity.User2;

public class ManyToMany {

	private EntityManagerFactory createEntityManagerFactory;

	@Before
	public void before() {
		// 通过 Persistence得到 EntityManagerFactory 实体管理工厂对象
		createEntityManagerFactory = Persistence.createEntityManagerFactory("jpa");

	}

	@After
	public void after() {
		if (createEntityManagerFactory != null) {
			createEntityManagerFactory.close();
		}
	}

	/**
	 * 测试多对一 关系哦 邮箱 和角色之间关系 多对一
	 */
	@Test
	public void Savetest() {
		// 通过实体管理工厂对象createEntityManagerFactory 对象获得entityManager 实体管理
		EntityManager entityManager = createEntityManagerFactory.createEntityManager();
		// 通过entityManager 实体管理对象 对象获得EntityTransaction 事务
		EntityTransaction transaction = entityManager.getTransaction();
		// 开启事务
		transaction.begin();

		// 获得User2对象
		User2 user2= new User2();
		user2.setUserName("张三");
		user2.setAddress("摊上利亚");
		user2.setPassWord("666666");
		
		Set<Role2> roles = new HashSet<Role2>();
	
		Role2 role2 = new Role2();
		role2.setUserName("李四");
		role2.setPassWord("555555");
		role2.setAddress("你挂啦呱");
		// 将角色添加给角色
		roles.add(role2);
		entityManager.persist(role2);
		
	
		
		// 持久化对像
		entityManager.persist(user2);// 保存邮箱
		// 通过transaction 提交事务
		transaction.commit();
		// 关闭实体管理
		entityManager.close();

	}


}
